package com.yupi.yupao.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.yupi.yupao.common.BaseContext;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.enums.TeamStatusEnum;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.model.domain.Invitation;
import com.yupi.yupao.model.domain.Team;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.domain.UserTeam;
import com.yupi.yupao.model.domain.dto.TeamQuery;
import com.yupi.yupao.model.domain.request.TeamJoinRequest;
import com.yupi.yupao.model.domain.request.TeamQuitRequest;
import com.yupi.yupao.model.domain.request.TeamUpdateRequest;
import com.yupi.yupao.model.vo.TeamUserMapVO;
import com.yupi.yupao.model.vo.TeamUserVO;
import com.yupi.yupao.model.vo.UserVO;
import com.yupi.yupao.model.vo.WxTokenVO;
import com.yupi.yupao.service.TeamService;
import com.yupi.yupao.mapper.TeamMapper;
import com.yupi.yupao.service.UserService;
import com.yupi.yupao.service.UserTeamService;
import com.yupi.yupao.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
* @author 李皮特
* @description 针对表【team(队伍)】的数据库操作Service实现
* @createDate 2024-05-07 11:21:34
*/
@Service
@Slf4j
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team>
    implements TeamService{

    @Resource
    private UserTeamService userTeamService;
    @Resource
    private UserService userService;
    //获取yml配置项
    @Value("${aliyun.endpoint}")
    private String endPoint;
    @Value("${aliyun.keyid}")
    private String accessKey;
    @Value("${aliyun.keysecret}")
    private String secreKey;
    @Value("${aliyun.bucketname}")
    private String bucketName;
    @Value("${AppID}")
    private String AppId;
    @Value("${AppSecret}")
    private String AppSecret;
    @Resource
    private RedisTemplate redisTemplate;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createTeam(Team team, User loginUser) {
//        1. 请求参数是否为空？
        if(team==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(loginUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
//        2. 是否登录，未登录不允许创建
//        3. 校验信息
//        a. 队伍人数 > 1 且 <= 20
        if(!(team.getMaxNum()>1&&team.getMaxNum()<=20)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍人数过长");
        }
//        b. 队伍标题 <= 20
        if(team.getName().length()>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍标题过长");
        }
//        c. 描述 <= 512
        if(team.getDescription().length()>512){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍描述过长");
        }
//        d. status 是否公开（int）不传默认为 0（公开）
        Integer status = Optional.ofNullable(team.getStatus()).orElse(0);
        TeamStatusEnum statusEnum = TeamStatusEnum.getEnumByValue(status);
        if(statusEnum==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍状态不满足要求");
        }
//        e. 如果 status 是加密状态，一定要有密码，且密码 <= 32
        if(TeamStatusEnum.SECRET.equals(statusEnum)){
            if(StringUtils.isBlank(team.getPassword())||team.getPassword().length()>32){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码设置不正确");
            }
        }
        Date expireTime=team.getExpireTime();
        if(expireTime==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍过期时间不能为空");
        }
        if(new Date().after(expireTime)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"超时时间 > 当前时间");
        }
//        f. 超时时间 > 当前时间
//        g. 校验用户最多创建 5 个队伍
        Long userId = loginUser.getId();
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        long TeamCount = this.count(queryWrapper);
        if(TeamCount>=5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"最多创建5个队伍");
        }
//        4. 插入队伍信息到队伍表
        team.setId(null);
        team.setUserId(userId);
        boolean result = this.save(team);
        if(!result||team.getId()==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"创建队伍失败");
        }
//        5. 插入用户 => 队伍关系到关系表
        UserTeam userTeam = new UserTeam();
        userTeam.setTeamId(team.getId());
        userTeam.setUserId(loginUser.getId());
        userTeam.setJoinTime(new Date());
        boolean userTeamResult = userTeamService.save(userTeam);
        if(!userTeamResult){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"创建队伍失败");
        }
        return team.getId();
    }

    @Override
    public TeamUserMapVO listTeams(TeamQuery teamQuery, boolean isAdmin) {
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        if(teamQuery!=null){
            Long teamQueryId = teamQuery.getId();
            if(teamQueryId!=null){
                queryWrapper.eq("id",teamQueryId);
            }
            List<Long> idList = teamQuery.getIdList();
            if(!CollectionUtils.isEmpty(idList)){
                queryWrapper.in("id",idList);
            }
            String name = teamQuery.getName();
            if(StringUtils.isNotBlank(name)){
                queryWrapper.like("name",name);
            }
            String description = teamQuery.getDescription();
            if(StringUtils.isNotBlank(description)){
                queryWrapper.like("description",description);
            }
            Integer maxNum = teamQuery.getMaxNum();
            if(maxNum!=null&&maxNum>0){
                queryWrapper.eq("maxNum",maxNum);
            }
            Long userId = teamQuery.getUserId();
            if(userId!=null&&userId>0){
                queryWrapper.eq("userId",userId);
            }
            Integer status = teamQuery.getStatus();
            TeamStatusEnum teamStatusEnum = TeamStatusEnum.getEnumByValue(status);
            if (teamStatusEnum==null){
                teamStatusEnum=TeamStatusEnum.PUBLIC;//默认队伍公开
            }
            //不是管理员并且队伍私有，不能修改
            if(!isAdmin&&teamStatusEnum.equals(TeamStatusEnum.PRIVATE)){
                throw new BusinessException(ErrorCode.NO_AUTH);
            }
//            queryWrapper.eq("status",teamStatusEnum.getValue());
        }
        //不展示已过期队伍
        // expireTime is null or expireTime > now()
        queryWrapper.and(qw -> qw.gt("expireTime", new Date()).or().isNull("expireTime"));
        List<Team> teamList;
        Long totalPage;//初始化总页数
       if(teamQuery.getPageNum()>0&&teamQuery.getPageSize()>0){
           IPage page=this.page(new Page<>(teamQuery.getPageNum(),teamQuery.getPageSize()),queryWrapper);
           page.getRecords().stream().forEach(System.out::println);
           teamList=page.getRecords();
           totalPage=page.getPages();
       }else{
           teamList = this.list(queryWrapper);
           totalPage=Long.valueOf(teamList.size());
       }

        if(CollectionUtils.isEmpty(teamList)){
            return new TeamUserMapVO();
        }
//        List<TeamUserVO> teamUserVOList=new ArrayList<>();
        TeamUserMapVO teamUserMapVO = new TeamUserMapVO();
        teamUserMapVO.setTotalPage(totalPage);
        List<TeamUserVO> teamUserVOList = teamUserMapVO.getTeamUserVOList();
        teamUserVOList=new ArrayList<>();
        for (Team team:teamList) {
            Long userId = team.getUserId();
            if(userId==null){
                continue;
            }
            User user = userService.getById(userId);
            TeamUserVO teamUserVO = new TeamUserVO();
            BeanUtils.copyProperties(team,teamUserVO);
            if(user!=null){
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user,userVO);
                teamUserVO.setCreateUser(userVO);
            }
            teamUserVOList.add(teamUserVO);
        }
        teamUserMapVO.setTeamUserVOList(teamUserVOList);
        return teamUserMapVO;
    }

    @Override

    public boolean updateTeam(TeamUpdateRequest teamUpdateRequest, User loginUser) {
        Long id = teamUpdateRequest.getId();
        if (id==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        //队伍是否存在
        Team team = this.getById(id);
        if(team==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍不存在");
        }

        //管理员和队伍创建者才能修改
        boolean isAdmin = userService.isAdmin(loginUser);
        log.info("loginUser.getId()!=team.getUserId():");
//        System.out.println(loginUser.getId());
//        System.out.println(team.getUserId());
//        System.out.println(loginUser.getId().equals(team.getUserId()));
        if((isAdmin)||(!loginUser.getId().equals(team.getUserId()))){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        TeamStatusEnum teamStatusEnum = TeamStatusEnum.getEnumByValue(teamUpdateRequest.getStatus());
        if(TeamStatusEnum.SECRET.equals(teamStatusEnum)){
            if(StringUtils.isBlank(teamUpdateRequest.getPassword())){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"加密队伍必须设置密码");
            }
        }
        Team updateTeam = new Team();

        BeanUtils.copyProperties(teamUpdateRequest,updateTeam);
        boolean result = this.updateById(updateTeam);

        return result;
    }

    @Override
    public boolean JoinTeam(TeamJoinRequest teamJoinRequest, User loginUser) {

        Long teamId = teamJoinRequest.getTeamId();
        Team team = this.getById(teamId);
        if(team==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍不存在");
        }
        //最大人数
        Integer maxNum = team.getMaxNum();
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        //不能加入自己的队伍 如果已加入不进行后续操作
        queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("teamId",teamId);
        queryWrapper.eq("userId",loginUser.getId());
        long hasJoinTeamNum = userTeamService.count(queryWrapper);
        if(hasJoinTeamNum>0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"已加入，不能重复添加");
        }
        queryWrapper.eq("teamId",teamId);
        long hasJoinTeamCount = userTeamService.count(queryWrapper);
        if(hasJoinTeamCount>=maxNum){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍人数已满");
        }
        Date expireTime = team.getExpireTime();
        if(expireTime!=null&&expireTime.before(new Date())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍已过期");
        }
        Integer status = team.getStatus();
        if(TeamStatusEnum.getEnumByValue(status).equals(TeamStatusEnum.PRIVATE)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不能加入私有队伍");
        }
        String password = teamJoinRequest.getPassword();
        if(TeamStatusEnum.getEnumByValue(status).equals(TeamStatusEnum.SECRET)){
            if(StringUtils.isBlank(password)||!password.equals(team.getPassword())){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码错误");
            }

        }
        //最多能加入5个队伍
        queryWrapper.eq("userId",loginUser.getId());
        //用户已经加入队伍数量
        long userHsaJoinNum = userTeamService.count(queryWrapper);
        if(userHsaJoinNum>5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"最多加入5个队伍");
        }

        //加入，修改队伍信息
        UserTeam userTeam = new UserTeam();
        userTeam.setUserId(loginUser.getId());
        userTeam.setTeamId(teamId);
        userTeam.setJoinTime(new Date());

        //TODO 加入队伍后是否要把消息历史记录删除？？？
        return userTeamService.save(userTeam);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean quitTeam(TeamQuitRequest teamQuitRequest, User loginUser) {
        if (teamQuitRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long teamId = teamQuitRequest.getTeamId();
        if (teamId == null || teamId <= 0){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Team team = this.getById(teamId);
        if (team == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"队伍不存在");
        }
        long userId = loginUser.getId();
        UserTeam queryUserTeam = new UserTeam();
        queryUserTeam.setUserId(userId);
        queryUserTeam.setTeamId(teamId);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>(queryUserTeam);
        long count = userTeamService.count(queryWrapper);
        if (count == 0 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"未加入队伍");
        }
        long teamHasJoinNum = this.countTeamUserByTeamId(teamId);
        // 队伍只剩一人，解散
        if (teamHasJoinNum == 1) {
            // 删除队伍
            this.removeById(teamId);
        } else {
            // 队伍还剩至少两人
            // 是队长
            if (team.getUserId() == userId) {
                // 把队伍转移给最早加入的用户
                // 1. 查询已加入队伍的所有用户和加入时间
                QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
                userTeamQueryWrapper.eq("teamId", teamId);
                userTeamQueryWrapper.last("order by id asc limit 2");
                List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
                if (CollectionUtils.isEmpty(userTeamList) || userTeamList.size() <= 1) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR);
                }
                UserTeam nextUserTeam = userTeamList.get(1);
                Long nextTeamLeaderId = nextUserTeam.getUserId();
                // 更新当前队伍的队长
                Team updateTeam = new Team();
                updateTeam.setId(teamId);
                updateTeam.setUserId(nextTeamLeaderId);
                boolean result = this.updateById(updateTeam);
                if (!result) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新队伍队长失败");
                }
            }
        }
        // 移除关系
        return userTeamService.remove(queryWrapper);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTeam(long id, User loginUser) {
        Team team = this.getById(id);
        if (team == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"队伍不存在");
        }
        long userId = loginUser.getId();
        if (team.getUserId() != userId) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"你不是当前队伍队长");
        }
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teamId",id);
        boolean res = userTeamService.remove(queryWrapper);
        if(!res){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"解散失败");
        }



        return this.removeById(id);
    }


    @Override
    public String fileUpload(@RequestParam(value = "file") MultipartFile file) {
        log.info(file.getContentType());
        if(file==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件不能为空");
        }

        if (file.getContentType() == null ||
                !(file.getContentType().equals("image/jpeg") || file.getContentType().equals("image/png"))) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 检查文件扩展名（忽略大小写）
        if (file.getOriginalFilename() != null && !(file.getOriginalFilename().toLowerCase().endsWith(".jpg") || file.getOriginalFilename().toLowerCase().endsWith(".png"))) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }else{
            log.info("文件大小："+file.getSize()+1*1024*1024);
            if(file.getSize()>=1 * 1024 * 1024){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件过大");
            }
        }
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKey, secreKey);
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid+fileName;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl+"/"+fileName;
            //调用方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //上传之后文件路径
            // https://ssyx-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endPoint+"/"+fileName;
            //返回
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
    }

    @Override
    public WxTokenVO getAccessToken() {
        // 先尝试从 Redis 获取 token
        String redisTokenKey = "wx_access_token";
        String accessToken = (String) redisTemplate.opsForValue().get(redisTokenKey); // 获取缓存中的token

        // 检查 Redis 中的 token 是否存在
        if (StringUtils.isNotBlank(accessToken)) {
            log.info("从缓存中获取到 access_token");
            WxTokenVO wxTokenVO = new WxTokenVO();
            wxTokenVO.setAccessToken(accessToken);
            return wxTokenVO;
        }

        // 如果缓存中没有 token 或 token 过期，发起请求获取新的 token
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "client_credential");
        map.put("appid", AppId);
        map.put("secret", AppSecret);

        // 发起 HTTP GET 请求
        String result = HttpClientUtils.doGet(accessTokenUrl, map);
        log.info("请求成功，请求结果为：" + result);

        // 解析请求结果，转换为 WxTokenVO
        Gson gson = new Gson();
        WxTokenVO wxTokenVO = gson.fromJson(result,WxTokenVO.class);

        // 将 token 存入 Redis，并设置过期时间 (单位是秒)
        if (wxTokenVO != null && wxTokenVO.getAccessToken() != null) {
            long expiresIn = wxTokenVO.getExpiresIn();
            redisTemplate.opsForValue().set(redisTokenKey, wxTokenVO.getAccessToken(), expiresIn, TimeUnit.SECONDS);
            log.info("将 access_token 存入缓存，过期时间为：" + expiresIn + " 秒");
        }

        return wxTokenVO;
    }


    // 保存组队邀请消息，设置24小时过期时间
    public void saveInvitation(Long senderId, Long receiverId, String message) {
//        String key = "team:invites:" + receiverId;
//
//        // 创建消息内容，使用Hash存储
//        String messageId = String.valueOf(System.currentTimeMillis()); // 使用时间戳作为消息ID
//        Invitation invitation = new Invitation(senderId, message, false);
//
//        // 保存消息到Redis，并设置24小时过期
//        redisTemplate.opsForHash().put(key, messageId, invitation);
//        redisTemplate.expire(key, Duration.ofHours(24));
    }

    // 获取未读消息
    public Map<Object, Object> getUnreadInvitations(Long receiverId) {
        String key = "team:invites:" + receiverId;

        // 获取所有消息（Redis Hash）
        Map<Object, Object> invitations = redisTemplate.opsForHash().entries(key);

        // 过滤未读的消息
        invitations.entrySet().removeIf(entry -> ((Invitation) entry.getValue()).isRead());
        return invitations;
    }

    // 标记消息为已读
    @Override
    public Boolean markInvitationsAsRead(Long teamId) {
        Long userId = BaseContext.getCurrentId();
        String key = "team:invites:" + userId;
        Invitation invitation = (Invitation) redisTemplate.opsForHash().get(key, String.valueOf(teamId));
        invitation.setRead(true);
        redisTemplate.opsForHash().put(key,String.valueOf(teamId),invitation);
        // 获取所有消息并更新isRead字段
//        Map<Object, Object> invitations = redisTemplate.opsForHash().entries(key);
//        for (Object messageId : invitations.keySet()) {
//            Invitation invitation = (Invitation) redisTemplate.opsForHash().get(key, messageId);
//            if (!invitation.isRead()) {
//                invitation.setRead(true);
//                redisTemplate.opsForHash().put(key, messageId, invitation);
//            }
//        }
        return true;
    }

    /**
     * 获取签名 OSS
     * @return
     */
    @Override
    public Map<String, String> getOSSPolicy() {
        //https://md-ossbucket.oss-cn-beijing.aliyuncs.com/QQ%E6%88%AA%E5%9B%BE20210609114525.png  host的格式为 bucketname.endpoint
        String host = "https://" + bucketName + "." + endPoint;

        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //格式化一个当前的服务器时间

        String dir = format+"/"; // 用户上传文件时指定的前缀,我们希望以日期作为一个目录

        Map<String, String> respMap =null; //返回结果
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKey, secreKey);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessKey);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }

        return respMap;

    }


    /**
     * 获取某队伍当前人数
     *
     * @param teamId
     * @return
     */
    private long countTeamUserByTeamId(long teamId) {
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        userTeamQueryWrapper.eq("teamId", teamId);
        return userTeamService.count(userTeamQueryWrapper);
    }


}




